﻿using System;
using Deer.Time;

namespace Telex;

sealed partial class RpcChannel
{
    public void Send(uint protocolId, byte[] request)
    {
        request ??= Array.Empty<byte>();
        if (!this.TryWriteSendPak(Guid.NewGuid(), protocolId, request))
        {
            this.logger.Error($"Failed to write A unidirectional Rpc message. Protocol: {protocolId}");
        }
    }

    public void Call(uint protocolId, byte[] request, CallResponseDelegate func)
    {
        request ??= Array.Empty<byte>();
        var uid = Guid.NewGuid();
        var unit = new ResponseUnit()
        {
            uid = uid,
            func = func,
            timestamp = TimeUtil.GetTimestamp(DateTime.UtcNow.AddSeconds(TIMEOUT))
        };

        if (!this.responseUnits.TryAdd(uid, unit))
        {
            this.logger.Error("Failed to register the internal callback.");
            throw new Exception("Failed to register the internal callback.");
        }
        
        if (!this.TryWriteRequestPak(uid, protocolId, request))
        {
            this.logger.Error($"Failed to write A bidirectional Rpc request message, protocol: {protocolId}");
            return;
        }
    }
}